# coding:utf-8
import json
import os
import re
import time
import pandas as pd
import requests
#from requests.packages.urllib3.exceptions import InsecureRequestWarning


# RSAC_files 251953718
# RSAC_page 251953669



class ConfluenceApi():
    def __init__(self, host, username, password):
        self.username = username
        self.password = password
        self.host = host
        self.auth = (self.username, self.password)
        # self.files_id = '251953718'
        # self.rsac_id = '251953669'
        self.type_id = {}

    '''
    @author: zhoujiashen
    @todo: 发布页面
    @params: title（页面标题） space（空间key） body（页面内容） ancestors（页面标题）
            "ancestors":[{"id":xxx}], //如果有父页面填写此参数
    '''

    def publishPage(self, title, space, body, ancestors=None, labels=None):
        headers = {
            'Content-Type': 'application/json',
        }

        data = {"type": 'page', "title": title, "space": {"key": space},
                "body": {"storage": {"value": body, "representation": "storage"}}, 'metadata': {'labels': labels}}
        if ancestors:
            data['ancestors'] = [{'id': ancestors}]
        #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        response = requests.post('%s/rest/api/content/' % self.host, headers=headers,
                                 data=json.dumps(data),
                                 auth=self.auth, verify=False,timeout=15)
        #print(response.text)
        return response.json()

    '''
    @author: zhoujiashen
    @todo: 删除界面
    @params: title（页面标题） space（空间key） body（页面内容） ancestors（页面标题）
            "ancestors":[{"id":xxx}], //如果有父页面填写此参数
    '''

    def deletePage(self, pid):
        response = requests.delete('%s/rest/api/content/%s' % (self.host,pid),auth=self.auth, verify=False,timeout=15)
        print(response.text)
        return response.json()


    '''
    @author: zhoujiashen
    @todo: 更新页面内容
    '''

    def updatePage(self, pid, title, body, spaceKey, ver=2, expand=None):
        headers = {
            'Content-Type': 'application/json',
        }

        data = {
            "id": pid,
            "type": "page",
            "title": title,
            "space": {
                "key": spaceKey
            },
            "body": {
                "storage": {
                    "value": body,
                    "representation": "storage"
                }
            },
            "version": {
                "number": ver
            }
        }
        if expand:
            for k, v in expand.items():
                data[k] = v
        #print(data)
        response = requests.put('%s/rest/api/content/%s' % (self.host, pid), headers=headers, data=json.dumps(data),
                                auth=self.auth, verify=False,timeout=60)
        #print(response.text)
        if 'statusCode' in response.json().keys():
            if response.json()['statusCode'] == 409:
                new_ver = int(response.json()['message'].split('Current version is: ')[-1]) + 1
                return self.updatePage(pid, title, body, spaceKey, new_ver, expand)
        #print(response.text)
        return response.json()

    '''
    @author: zhoujiashen
    @todo: 插入新标签
    @params: lebels 标签列表 pid 页面id
    '''

    def addLabel(self, labels, pid):
        headers = {
            'Content-Type': 'application/json',
        }

        # data = '[{"prefix": "global", "name": "abc"}]'
        data = json.dumps(labels)
        response = requests.post('%s/rest/api/content/%s/label' % (self.host, pid), headers=headers, data=data,
                                 auth=self.auth, verify=False,timeout=15)
        print(response.text)
        return response.json()

    '''
    @author: zhoujiashen
    @todo: 上传附件
    @params: path:附件地址 name:Confluence中显示的文件名称 pid:内容ID
    '''

    def uploadFile(self, path, name, pid):
        headers = {
            'X-Atlassian-Token': 'no-check',
        }

        files = {
            'file': (name, open(path, 'rb')),
        }
        response = requests.post('%s/rest/api/content/%s/child/attachment' % (self.host, pid),
                                 headers=headers, files=files, auth=self.auth, verify=False)
        print(response.status_code,'--------------上传调试')
        #files.close()
        return response.json()

    '''
    @author: zhoujiashen
    @todo: 搜索
    @params: spaceKey(空间key) title(标题) expand(额外参数)
    '''

    def search(self, title, spaceKey, expand=None):
        params = (
            ('title', title),
            ("space", {"key": spaceKey}),
        )

        if expand:
            params = (
                ('title', title),
                ("space", {"key": spaceKey}),
                ("ancestors",expand['ancestors'])
            )

        #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        response = requests.get('%s/rest/api/content' % self.host, params=params,
                                auth=self.auth, verify=False,timeout=30)

        #print(response.text)
        return response.json()

    def browse(self, pid):
        params = (
            ('expand', 'body.storage'),
        )

        response = requests.get('%s/rest/api/content/%s' % (self.host, pid), params=params,
                                auth=self.auth, verify=False,timeout=15)
        return response.json()

    def getPageFile(self, pid):
        response = requests.get('%s/rest/api/content/%s/child/attachment' % (self.host, pid), auth=self.auth,
                                verify=False,timeout=30)
        return response.json()

    def getExcelContent(self, path):
        try:
            e = pd.read_excel(path)
        except:
            e = pd.read_excel(path, engine='openpyxl')

        return e

    def insertItem(self, row):

        if len(self.search(row['ID'])['results']) == 0:
            pass

    def main(self):
        df = pd.read_excel('rsa1621937684.xlsx', engine='openpyxl')
        cls = {}
        now_dir = os.listdir(os.getcwd())
        for i in df.index.tolist():
            ID = df.loc[i]['ID']
            Delivery_Format = df.loc[i]['Delivery Format']
            Track = df.loc[i]['Track']
            if type(Track) != float and type(Track) != None:
                choice = Track
            Session_Classification = df.loc[i]['Session Classification']
            Topic = df.loc[i]['Topic']
            Title = df.loc[i]['Title']
            Speaker = df.loc[i]['Speaker']
            Abstract = df.loc[i]['Abstract']
            pdf_path = df.loc[i]['pdf_path']
            video_path = df.loc[i]['video_path']

    def check_class(self, Delivery_Format, Track):
        pass

    def labels_upload(self,id, labelname):
        t = time.time()
        a = int(round(t * 1000))
        headers = {

            'Content-Type': 'application/json',

        }
        data = [{
            'name': labelname,
            'id': a
        }]
        url = '%s/rest/ui/1.0/content/%s/labels' % (self.host,id)
        response = requests.post(url, headers=headers, data=json.dumps(data),
                                auth=self.auth, verify=False,timeout=15)
        #print(response.text)
        return response.json()

    def push_frost(self):
        for dir in ['E:\\NSFOCUS\\bsa_takg\\lib\\2019年', 'E:\\NSFOCUS\\bsa_takg\\lib\\2020年',
                    'E:\\NSFOCUS\\bsa_takg\\lib\\2021年']:
            print(dir)
            for child_dir in os.listdir(dir.decode('utf-8')):
                print(child_dir)
                ancestor_id = self.search(title=child_dir, spaceKey='spider')['results'][0]['id']
                file_path = dir + '\\' + child_dir.encode('utf-8')
                for file in os.listdir(file_path.decode('utf-8')):
                    # if '.html' in file:
                    #     title = file.replace('.html','')
                    #     if not self.search(title=title, spaceKey='AR')['results']:
                    #         with open (file_path.decode('utf-8')+'\\'+file,'r') as f:
                    #             content = f.read()
                    #         bd = '''<ac:structured-macro ac:name=\"html\">
                    #             <ac:plain-text-body><![CDATA[
                    #             <html>%s</html>
                    #             ]]></ac:plain-text-body>
                    #             </ac:structured-macro>
                    #             '''%(content)
                    #         print self.publishPage(title, space='AR', body=bd,ancestors=ancestor_id)
                    if '.xlsx' in file:
                        title = file.replace('.xlsx', '')
                        check_page = self.search(title=title, spaceKey='AR')['results']
                        if not check_page:
                            print(self.publishPage(title, space='spider',
                                                   body='<p><ac:link><ri:attachment ri:filename="%s.xlsx" /></ac:link></p>' % title,
                                                   ancestors=ancestor_id))
                        else:
                            page_id = check_page[0]['id']
                            # browse_content = self.browse(page_id)['body']['storage']['value']
                            files = self.getPageFile(page_id)['results']
                            if len(files) == 0:
                                self.uploadFile(file_path.decode('utf-8') + '\\' + file, file, page_id)
# def myFunc():
#     time.sleep(4)
#     print("dshjh")


if __name__ == '__main__':
    # c = ConfluenceApi('https://secplat.intra.nsfocus.com', 'zhoujiashen3', 'eATn8N69y') # 能创
    # c = ConfluenceApi('http://192.168.11.133:8090', 'admin', 'admin')  # AR
    # for u in range(0,1000):
        #publishPage(str(u), space='spider', body=str(u), ancestors=str('3113454'))
    # for i in range(0,100):
    #     t=threading.Thread(target=c.search(title='a',spaceKey='spider'))
    #     t.setDaemon(True)
    #     t.start()
    #     t.join(30)
    #     print('超时三十秒')
    #c.publishPage("2021年11月", space='spider', body='', ancestors='3113893')
    c = ConfluenceApi('https://ar.intra.nsfocus.com','ar1','tpo@31580')
    #a=c.search(title='2021年11月', spaceKey='AR')['results'][0]['id']
    # print(a)
    #w=c.search('20211101'.strip(), spaceKey='AR')
    #print(w)
    c.uploadFile('C:\\Users\\nsfocus\\PycharmProjects\\pythonProject\\Ar_spider_gui——new\\download\\IDC IBM Security Strategy Update — Clear on Zero Trust, XDR, and Ecosystems But Doubts on the Services-Led GTM - 2021 Dec Figure 2.ppt','a','2918734')
    # da='760953'
    # print(da)
    # bd=c.browse(da)['body']['storage']['value']
    # #print(bd)
    # title=c.browse(da)['title']
    # try:
    #     old_cs = '.MuiGrid-grid-lg-7 {\n    flex-grow: 0;\n    max-width: 58.333333%;\n    flex-basis: 58.333333%;\n  }'
    #     new_cs = '.MuiGrid-grid-lg-7 {\n    flex-grow: 0;\n    max-width: 100%;\n    flex-basis: 58.333333%;\n  }'
    #     old_cs1 = '.MuiGrid-grid-md-7 {\n    flex-grow: 0;\n    max-width: 58.333333%;\n    flex-basis: 58.333333%;\n  }'
    #     new_cs1 = '.MuiGrid-grid-md-7 {\n    flex-grow: 0;\n    max-width: 100%;\n    flex-basis: 58.333333%;\n  }'
    #     bd = bd.replace(old_cs, new_cs)
    #     bd = bd.replace(old_cs1, new_cs1)
    # except:
    #     pass
    # #bd=bd.replace('ar.nsfocus','ar.intra.nsfocus')
    # try:
    #     a=re.findall(r'href="https://ar.nsfocus.com/download.attachments/[0-9]+/',bd)
    #     bd = bd.replace(a[0], 'href="https://ar.intra.nsfocus.com/download/attachments/%s/' % da)
    #     print(a)
    # except:
    #     pass
    # c.updatePage(da,title,bd,'AR')
    # try:
    #     b=re.findall(r'href="https://ar.nsfocus.com/download.attachments/[0-9]+/',bd)[1]
    #     bd = bd.replace(b, 'href="https://ar.intra.nsfocus.com/download/attachments/%s/' % da)
    #     print(b)
    # except:
    #     pass
    # try:
    #     q=re.findall(r'href="https://ar.nsfocus.com/download.attachments/[0-9]+/',bd)[2]
    #     bd = bd.replace(q, 'href="https://ar.intra.nsfocus.com/download/attachments/%s/' % da)
    #     print(q)
    # except:
    #     pass



    #print(title='20211029—从2021云栖大会看AI与大数据新趋势'['results'])
    # print(c.publishPage('tedsdsdst', space='AR', body='dhjhds1245j', ancestors=a)['id'])
    #print (c.publishPage('fsdfsdfsdfdf','spider','dasdsafa','3112998'))
    #c.labels_upload('3113338','dhjh')
    # a=c.search('20211029—从2021云栖大会看AI与大数据新趋势','AR')['results']
    # print(a)
    #c.publishPage(title='2021年11月')
    # fp = open('C:\\Users\\nsfocus\\Desktop\\新建文本文档 12.html', 'r', encoding='utf-8')
    #
    # bd = fp.read()
    # c.updatePage('325845073','20211028—IDC FutureScape: Worldwide Future of Trust 2022 Predictions',bd,'AR')
    #q="327155776"
    # bd=c.browse(q)['body']['storage']['value']
    # # print(bd)
    # # a= ''
    # # b=''
    # b='https://ar.nsfocus.com/download/attachments/%s/IDC Worldwide Digital Loss Technologies Market Shares, 2020 DLP Is Dead, Long Live DLP - 2021 Oct share.xlsx'%q
    # a = "/getfile.dyn?containerId=US48261521&amp;attachmentId=47433581"#/getfile.dyn?containerId=US46350821&amp;attachmentId=47433743
    # bd = bd.replace(a,b)
    # #bd = bd.replace("id=\"main\"",'')
    # #print(bd)
#328990781
    #c.uploadFile( path, name, pid)
    #print(c.browse(a)['body']['storage']['value'])
    # c.push_frost()
    # c.browse('270532624')
    # print(c.search('2021年', 'AR')['results'][0]['id'])
    # print(c.uploadFile('config.json','config.json','308969489'))
    # print(c.deletePage('301662268'))
    # c.publishPage('testLab222el223','~zhoujiashen3','test',ancestors='262012929',labels=[{"prefix": "global", "name": "gartner"}])
    # c.addLabel([{"prefix": "global", "name": "gartner"}],'269975572')
    # c.updatePage("269975572",'testLabel223','test','~zhoujiashen3',expand={'metadata':{'labels':[{'name':'gartner'}]}})
    # print(c.search('Better Call Brussels - News on European Cyber Security and eID Regulation','nczxlh'))
    # print(c.browse('315234635'))
    # print(ConfluenceApi().publishPage(title='RMG-T15', space='~zhoujiashen3', body=bd1,ancestors='251953718'))
    # df = c.getExcelContent('rsa1621581152.xlsx')
    # for i in df.index.tolist():
    #     c.insertItem(df.loc[i])
    #     break
    # print(c.getPageFile('252510423'))
    # print(ConfluenceApi().search(title='RMG-T15', spaceKey='~zhoujiashen3'))
    # ConfluenceApi()publishPage
    # print(c.uploadFile(r'E:\迅雷下载\v-85006abb-bd52-4e07-af16-fbc1c7c654b9.mp4','v-85006abb-bd52-4e07-af16-fbc1c7c654b9.mp4','252510423'))

    # c=ConfluenceApi('https://ar.nsfocus.com','ar1','tpo@31580')#328990797
    # c.updatePage('329777157',title='djk',body='jkj',spaceKey='AR')

















